set(DBCSR_PROGRAM_SRCS_FTN dbcsr_example_1.F dbcsr_example_2.F
                           dbcsr_example_3.F dbcsr_tensor_example_1.F)

set(DBCSR_PROGRAM_SRCS_CPP dbcsr_example_3.cpp dbcsr_tensor_example_2.cpp)

# Compile Fortran examples
foreach (dbcsr_program_src ${DBCSR_PROGRAM_SRCS_FTN})
  get_filename_component(dbcsr_program_name ${dbcsr_program_src} NAME_WE)
  add_executable(${dbcsr_program_name} ${dbcsr_program_src})
  target_link_libraries(${dbcsr_program_name} dbcsr)
  if (OpenMP_FOUND)
    target_link_libraries(${dbcsr_program_name} OpenMP::OpenMP_Fortran)
  endif ()

  # with the Intel compiler CMake 3.12 seems to forget that the source is
  # actually Fortran and needs to be told explicitly:
  set_target_properties(${dbcsr_program_name} PROPERTIES LINKER_LANGUAGE
                                                         Fortran)
endforeach ()

# override -Werror for certain translation units
if ((CMAKE_Fortran_COMPILER_ID STREQUAL "GNU")
    AND (CMAKE_Fortran_COMPILER_VERSION VERSION_GREATER_EQUAL 10))
  set_source_files_properties(dbcsr_tensor_example_1.F PROPERTIES COMPILE_FLAGS
                                                                  -Wno-error)
endif ()

# Compile C++ examples
if (WITH_C_API)
  foreach (dbcsr_program_src ${DBCSR_PROGRAM_SRCS_CPP})
    get_filename_component(dbcsr_program_name ${dbcsr_program_src} NAME_WE)
    set(dbcsr_program_name ${dbcsr_program_name}_cpp)
    add_executable(${dbcsr_program_name} ${dbcsr_program_src})
    target_link_libraries(${dbcsr_program_name} dbcsr_c MPI::MPI_CXX)
    set_target_properties(${dbcsr_program_name} PROPERTIES LINKER_LANGUAGE
                                                           Fortran)
    if (OpenMP_FOUND)
      target_compile_options(${dbcsr_program_name} PRIVATE ${OpenMP_CXX_FLAGS})
      target_link_libraries(${dbcsr_program_name} OpenMP::OpenMP_Fortran)
    endif ()

    if (CMAKE_CXX_COMPILER_ID STREQUAL "Cray")
      # for recent Cray compiler versions CMake doesn't know
      target_compile_options(${dbcsr_program_name} PRIVATE "-hstd=c++14")
    else ()
      target_compile_features(${dbcsr_program_name} PRIVATE cxx_std_14)
    endif ()
  endforeach ()
endif ()

# =================================== DOCUMENTATION GENERATION Copy example
# source files into the build directory so that their documentation can be
# generated by FORD

set(DBCSR_PROGRAM_SRCS ${DBCSR_PROGRAM_SRCS_FTN} ${DBCSR_PROGRAM_SRCS_CPP})

# Make a list of the copy commands
set(example_copy_commands)
foreach (example ${DBCSR_PROGRAM_SRCS})
  list(
    APPEND
    example_copy_commands
    COMMAND
    ${CMAKE_COMMAND}
    -E
    copy
    ${CMAKE_SOURCE_DIR}/examples/${example}
    ${CMAKE_BINARY_DIR}/examples)
endforeach ()

add_custom_target(
  doc_copy_examples
  COMMENT "Copy examples for documentation generation"
  COMMAND mkdir -p ${CMAKE_BINARY_DIR}/examples ${example_copy_commands}
  VERBATIM)
